{{- $analytics := .Scratch.Get "analytics" | default dict -}}

{{- if $analytics.enable -}}
    {{- /* Google Analytics */ -}}
    {{- with $analytics.google.id -}}
        {{- if $analytics.google.gtag -}}
            <script>
                window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag('js', new Date());
                gtag('config', '{{ . }}'{{ if $analytics.google.anonymizeIP }}, { 'anonymize_ip': true }{{ end }});
            </script>
            {{- printf "https://www.googletagmanager.com/gtag/js?id=%v" . | dict "Async" true "Source" | partial "plugin/script.html" -}}
        {{- else -}}
	    <script>
                (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
                })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

	        ga('create', '{{ . }}', 'auto');
	        {{ if $analytics.google.anonymizeIP }}ga('set', 'anonymizeIp', true);{{ end }}
	        ga('send', 'pageview');
	    </script>
        {{- end -}}
    {{- end -}}

    {{- /* Fathom Analytics */ -}}
    {{- with $analytics.fathom.id -}}
        <script>
            window.fathom=window.fathom||function(){(fathom.q=fathom.q||[]).push(arguments);};
            fathom('set', 'siteId', '{{ . }}');
            fathom('trackPageview');
        </script>
        {{- dict "Source" ($analytics.fathom.server | default "cdn.usefathom.com" | printf "https://%v/tracker.js") "Async" true "Attr" "id=fathom-script" | partial "plugin/script.html" -}}
    {{- end -}}

    {{- /* Yandex Metrica */ -}}
    {{- if $analytics.yandex.id -}}
    <script>
        (function(m,e,t,r,i,k,a){m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};
            m[i].l=1*new Date();k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)})
        (window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym");

        ym({{ $analytics.yandex.id }}, "init", {
            clickmap:true,
            trackLinks:true,
            accurateTrackBounce:true,
            webvisor:{{ $analytics.yandex.webvisor }}
        });
    </script>
    <noscript><div><img src="https://mc.yandex.ru/watch/{{ $analytics.yandex.id }}" style="position:absolute; left:-9999px;" alt="" /></div></noscript>
    {{- end -}}
{{- end -}}
